{% extends 'index.html' %}
{% block ace-content %}
<link href="/static/dist/css/smart_wizard.css" rel="stylesheet" type="text/css" />
<link href="/static/dist/css/smart_wizard_theme_circles.css" rel="stylesheet" type="text/css" />
<link href="/static/dist/css/smart_wizard_theme_arrows.css" rel="stylesheet" type="text/css" />
<link href="/static/dist/css/smart_wizard_theme_dots.css" rel="stylesheet" type="text/css" />
{% endblock %}
{% block page-content %}
<div id="page-wrapper">
    <div class="row">
         <div class="col-lg-12">
              <h1 class="page-header"><i class="fa fa-github"></i><code>{{order.order_project.project_name}}</code> 项目部署</h1>
         </div>
                <!-- /.col-lg-12 -->
    </div>
	<div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
 						<i class="fa    fa-gears"></i>代码部署
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-lg-4">
                                <legend><i class="fa  fa-paper-plane"></i>部署服务器</legend>
                                    <form role="form" id="deployRun" class="main form-horizontal" >{% csrf_token %}
										<fieldset>															
											<div class="form-group">
												 <label class="col-sm-2 control-label">项目名称</label>
												 <div class="col-sm-6">
												 	<input type="text" class="form-control" name="project_name" value="{{order.project_order.order_project.project_name}}"  class="input-xlarge" readonly="readonly" />
												 	<input type="hidden" class="form-control" name="project_uuid" value="{{order.project_order.order_project.project_uuid}}" readonly="readonly"/>
												 </div>
											</div>
											<div class="form-group">
												 <label class="col-sm-2 control-label">项目环境</label>
												 <div class="col-sm-6">
	                               					{% if order.project_order.order_project.project_env == 'sit' %}
	                                					<span class="label label-success">测试环境</span>
	                                				{% elif order.project_order.order_project.project_env == 'qa' %}
	                                					<span class="label label-warning">预生产环境</span>
	                                				{% elif order.project_order.order_project.project_env == 'uat' %}
	                                					<span class="label label-danger">生产环境</span>
	                                				{% endif %}
												 </div>
											</div>											
		                                     <div class="form-group">
		                                            <label class="col-sm-2 control-label">目标服务器</label>
		                                            <div class="col-sm-6">
			                                            <select multiple class="selectpicker" data-live-search="true" name="project_server" id="project_server" required>
			                                            	{% for ds in serverList %}
			                                            		<option name="project_server" selected="selected"  value="{{ds.server}}">{{ds.server}}</option>
			                                            	{% endfor %}
			                                            </select>
		                                            </div>
		                                      </div> 											
											<div class="form-group">
												 <label class="col-sm-2 control-label">更新主题</label>
												 <div class="col-sm-6">												 	
                                            		<input class="form-control" value="{{order.order_subject}}" readonly="readonly">
												 </div>
											</div>	
					
											<div class="form-group">
												 <label class="col-sm-2 control-label">更新内容</label>
												 <div class="col-sm-6">                                           
                                            		<textarea class="form-control" rows="3" readonly="readonly">{{order.project_order.order_content}}</textarea>
												 </div>
											</div>												
											{% if order.project_order.order_project.project_model == 'branch' and order.project_order.order_project.project_repertory == 'git'  %}																
											<div class="form-group">
												 <label class="col-sm-2 control-label">分支</label>
												 <div class="col-sm-6">
													<input type="text" class="form-control" name="project_branch" value="{{order.project_order.order_branch}}"  class="input-xlarge" readonly="readonly"/>							 	
												 </div>
											</div>													
											
											<div class="form-group">
												 <label class="col-sm-2 control-label">更新版本</label>
												 <div class="col-sm-6">
													<div class="input-group">
														<input type="text" class="form-control " name="project_version" value="{{order.project_order.order_comid}}" readonly="readonly">
														<span class="input-group-btn">
															<button class="btn btn-success" type="button"  data-toggle="modal" data-target="#myModal" >
																查看
															</button>
														</span>
													</div>											 
												</div>
											</div>
											{% elif order.project_order.order_project.project_model == 'tag' and  order.project_order.order_project.project_repertory == 'git'  %}
											<div class="form-group">
												 <label class="col-sm-2 control-label">Tag版本</label>
												 <div class="col-sm-6">
												 	{% if order.project_order.order_tag %}
												 		<input type="text" class="form-control" name="project_branch" value="{{order.project_order.order_tag}}"  class="input-xlarge" readonly="readonly"/>
												 	{% else %}
														<input type="text" class="form-control" name="project_branch"   class="input-xlarge" readonly="readonly"/>	
													{% endif %}					 	
												 </div>
											</div>	
											{% else %}
												<div class="form-group">
													 <label class="col-sm-2 control-label">更新版本</label>
													 <div class="col-sm-6">
														<div class="input-group">
															<input type="hidden" type="text" class="form-control " name="project_branch" value="{{order.project_order.order_comid}}" readonly="readonly">
															<input type="text" class="form-control " name="project_version" value="{{order.project_order.order_comid}}" readonly="readonly">
															<span class="input-group-btn">
																<button class="btn btn-success" type="button"  data-toggle="modal" data-target="#myModal" >
																	查看
																</button>
															</span>
														</div>											 

													</div>
												</div>																							
											{% endif %}																																													
											
											<div class="form-group">
												 <label class="col-sm-2 control-label">部署指派</label>
												 <div class="col-sm-6">												 	
                                            		<input class="form-control" value="{{order.order_user}}" readonly="readonly">
												 </div>
											</div>	
											<div class="form-group">
												 <label class="col-sm-2 control-label">紧急程度</label>
												 <div class="col-sm-6">	
										         	{% if order.project_order.order_level == 1 %}
										         		<button  type="button" class="btn btn-outline btn-default disabled">紧急</button>
										         	{% else %}
										         		<button  type="button" class="btn btn-outline btn-warning disabled">非紧急</button>
										         	{% endif %} 
												 </div>
											</div>																						
											<div class="form-group">
												 <label class="col-sm-2 control-label">工单状态</label>
												 <div class="col-sm-6">	
										         	{% if order.order_status == 8 %}
										         		<button  type="button" class="btn btn-outline btn-info disabled">已授权</button>							         	
										         	{% elif order.order_status == 7 %}
										         		<button  type="button" class="btn btn-outline btn-danger" ><del>已撤销</del></button>
										         	{% elif order.order_status == 2 %}
										         		<button  type="button" class="btn btn-outline btn-warning disabled">审核中</button>
										         	{% elif order.order_status == 3 %}
										         		<button  type="button" class="btn btn-outline btn-success disabled" >已部署</button>
										         	{% endif %}	
												 </div>
											</div>	
											{% if order.order_perm == 'pass' and order.order_status == 0 or order.order_status == 2 and order.order_perm == 'pass'%}
											<div class="form-group" id="permOrder">
												 <label class="col-sm-2 control-label">工单操作</label>
												 <div class="col-sm-6">	
										         	{% if order.order_status == 0 %}
										         		<button  type="button" class="btn btn-outline btn-success" onclick="updateOrderStatus(this,{{ order.id }},'disable',7)">撤销部署</button>							         	
										         	{% elif order.order_status == 2 %}
										         		<button  type="button" class="btn btn-outline btn-success" onclick='updateOrderStatus(this,{{ order.id }},"auth",8)'>确认授权</button>
										         	{% endif %}	
												 </div>
											</div>		
											{% endif %}																			
											</fieldset>
											<legend></legend>
											<div class="form-group">
											<label class="col-sm-3 control-label"></label>
											{% if order.order_status == 8 %}
												<button type="button"  class="btn btn-default disabled">完成部署</button>
									 			<button type="button"  class="btn btn-default" onclick="runDeploy(this)" >点击部署</button>
									 		{% else %}
									 			<button type="button"  class="btn btn-default disabled">完成部署</button>
									 			<button type="button"  class="btn btn-default disabled">确认部署</button>
									 		{% endif %}
									 		</div>																		 		
									</form>                                        
                                </div>
                                <!-- /.col-lg-6 (nested) -->
                                <div class="col-lg-8">
                                    <legend><i class="fa  fa-paper-plane-o"></i>部署结果</legend>       
								    <div class="form-group">
								
								        <!-- SmartWizard html -->
								        <div id="smartwizard">
								            <ul>
								                <li><a href="#get_code">获取代码<br /><small>pull code</small></a></li>
								                {% if order.project_order.order_project.project_type == 'compile' %}
								                <li><a href="#deploy_code">编译代码<br /><small>deploy code</small></a></li>
								                {% endif %}
								                <li><a href="#tar_code">打包代码<br /><small>pack code</small></a></li>
								                <li><a href="#rsync_code">部署代码<br /><small>rsyn code</small></a></li>
								                {% if order.project_order.order_project.project_remote_command %}
												<li><a href="#cmd_code">执行命令<br /><small>remote command</small></a></li>
												{% endif %}
								            </ul>								
								        </div>
								        <br>
	  									<div class="well well-lg" style="background:#000000; color:#ADFF2F">
					                        <div id="result">
											     {% if order.order_status == 0 %}
											         	<i class="fa fa-smile-o"></i>让我们开始部署之旅吧~							         	
											     {% elif order.order_status == 1 %}
											         	<i class="fa fa-frown-o"></i>Ops！任务被取消了~
											     {% elif order.order_status == 2 %}
											            <i class="fa fa-meh-o"></i>嘿、快去找那家伙授权吧~
											     {% elif order.order_status == 3 %}
											         	<i class="fa fa-smile-o"></i>下次合作愉快~
											     {% endif %}				                        
					                        </div>
					                    </div> 								
								
								    </div>				                                                   
                                <!-- /.col-lg-6 (nested) -->
                            </div>                                
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
	<!-- 模态框（Modal） -->
	<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog" style="width: 70%;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						&times;
					</button>
					<h4 class="modal-title" id="myModalLabel">
						<code>{{order.order_project.project_name}}</code>项目<code>{{order.project_order.order_comid|slice:":7"}}</code>版本提交历史
					</h4>
				</div>
				<div class="modal-body">
					<div id="version_result">
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭
					</button>
					<button type="button" class="btn btn-primary" onclick="getVersion(this,'{{order.project_order.order_branch}}','{{order.project_order.order_comid}}')">
						点击查看
					</button>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal -->
	</div>        
	
	<div class="modal fade" id="myDeployModal" tabindex="-1" role="dialog" aria-labelledby="myDeployModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" 
							aria-hidden="true">×
					</button>
					<h4 class="modal-title" id="myDeployLabel">
						部署进度
					</h4>
				</div>
				<div class="modal-body">
					<div id="noDeployServerList">
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-success" onclick="finishDeploy(this)">
						完成部署
					</button>				
					<button type="button" class="btn btn-primary" 
							data-dismiss="modal">继续部署
					</button>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal-dialog -->
	</div><!-- /.modal -->	
	    
</div>


<script type="text/javascript" src="/static/dist/js/jquery.smartWizard.min.js"></script>
<script type="text/javascript">

	$(document).ready(function(){
		
	    // Step show event
	    $("#smartwizard").on("showStep", function(e, anchorObject, stepNumber, stepDirection, stepPosition) {
	
	    });
	
	    $('#smartwizard').smartWizard("reset");
	
	    // Smart Wizard
	    $('#smartwizard').smartWizard({
	            selected: 0,
	            theme: 'arrows',
	            transitionEffect:'fade',
	            showStepURLhash: true,
	
	    });
	
	
	});

{% if order.order_perm == 'pass' and order.order_status == 8 or order.order_status == 2 and order.order_perm == 'pass' %}
	function updateOrderStatus(obj,id,model,status){
		if (model == 'auth' || model == 'finish' ){
			if (model == 'auth'){
				var txt=  "是否确认授权？";
				var title = "部署工单授权";
			}
			else if (model == 'finish'){
				var txt=  "是否确认完成？";
				var title = "部署工单完成";				
			};
			var option = {
				title: title,
				btn: parseInt("0011",2),
				onOk: function(){
					$.ajax({
						  type: 'PUT',
						  url: '/api/orders/{{order.id}}/',
						  data: {
							  "id":id,
							  "order_status":status
						  },
					      success:function(response){			            
				                window.wxc.xcConfirm("授权成功", window.wxc.xcConfirm.typeEnum.success);
				   /*              location.reload(); */
						},
			            error:function(response){
			            	window.wxc.xcConfirm("请求数据错误！", window.wxc.xcConfirm.typeEnum.error);
			            },							  
						});
				},
				onCancel:function(){	
				},
				onClose:function(){
				}
			}
			window.wxc.xcConfirm(txt, "custom", option);				
		}
		else if (model == 'disable'){
			window.wxc.xcConfirm("撤销原因：", window.wxc.xcConfirm.typeEnum.input,{
				onOk:function(result){
					if (result.length == 0){
						/* 如果没有输入字符串则直接退出 */
						return;
					};
					$.ajax({
						  type: 'PUT',
						  url: '/api/orders/{{order.id}}/',
						  data: {
							  'order_cancel':result,
							  'id':id,
							  "order_status":status
						  },
					      success:function(response){	
				                if (response["code"]=="200"){ 
				                	window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
				                }
					        	else{
					        		window.wxc.xcConfirm("撤销失败：" + response["msg"], window.wxc.xcConfirm.typeEnum.error);
					        	};	
					        	location.reload();
						},
			            error:function(response){
			            	btnObj.removeAttr('disabled');
			            	window.wxc.xcConfirm("服务器响应错误，撤销失败", window.wxc.xcConfirm.typeEnum.error);
			            },							  
						});
					
				}
			})			
		}		
	}
{% endif %}
		
{% if order.order_status == 8 %}
	function finishDeploy(obj){
		$.ajax({
		  type: 'PUT',
		  url: '/api/orders/{{order.id}}/',
		  data: {
			  "id":{{order.id}},
			  "model":'finish',
			  "order_status":3
		  },
			success:function(response){
					window.wxc.xcConfirm("部署完成", window.wxc.xcConfirm.typeEnum.success);
					location.reload();				
			},
	    	error:function(response){
	    		window.wxc.xcConfirm("部署失败", window.wxc.xcConfirm.typeEnum.error);
	    		clearInterval(interval);
	    	}
	});			
	}
	
	function runDeploy(obj) {
		var btnObj = $(obj);
		$('#smartwizard').smartWizard("reset");
		btnObj.attr('disabled',true);
		var form = document.getElementById('deployRun');
		var post_data = {};
		for (var i = 1; i < form.length; ++i) {
			var name = form[i].name;
			var value = form[i].value;
			var project = name.indexOf("project_");
			if ( project==0 && value.length==0){
				window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
				return false;
			}
			else if (name.length > 0 && value.length > 0){
				post_data[name] = value;
			};
			
		};
		$("#result").html("服务器正在处理，请稍等。。。");
		/* 轮训获取结果 开始  */
	   var interval = setInterval(function(){  
	        $.ajax({  
	            url : '/deploy_result/{{order.project_order.order_project.id}}/',  
	            type : 'post', 
	            data:post_data,
	            success : function(result){
	            	if (result["msg"] !== null ){
						if(result["msg"].indexOf("[Pack start") == 0){
	            			$('#smartwizard').smartWizard("next");
	            		}
						{% if order.project_order.order_project.project_type == 'compile' %}
						else if(result["msg"].indexOf("[DEPLOY start") == 0){
	            			$('#smartwizard').smartWizard("next");
	            		}
						{% endif %}
						else if(result["msg"].indexOf("[RSYNC start") == 0){
	            			$('#smartwizard').smartWizard("next");
	            		}else if(result["msg"].indexOf("[CMD start") == 0){
	            			$('#smartwizard').smartWizard("next");
	            		}
	            		$("#result").append("<p>"+result["msg"]+"</p>"); 						
	            		if (result["msg"].indexOf("[Done]") == 0){
	            			clearInterval(interval);
	            			/* 更新数据库-更新完成 */	
	            			if (noDeployServer.length == 0){
	            				$.ajax({
	            					  type: 'PUT',
	            					  url: '/api/orders/{{order.id}}/',
	            					  data: {
	            						  "id":{{order.id}},
	            						  "model":'finish',
	            						  "order_status":3
	            					  },
	            						success:function(response){
	            							window.wxc.xcConfirm("部署完成", window.wxc.xcConfirm.typeEnum.success);
	            							$('#permOrder').remove();
	            							btnObj.attr('disabled',true);	            								
	            							
	            						},
	            				    	error:function(response){
	            				    		window.wxc.xcConfirm("部署成功,但是未能更新工单状态", window.wxc.xcConfirm.typeEnum.error);
	            				    		clearInterval(interval);
	            				    	}
	            				});			            				
	            			}
	            			else{
	            				var liStr = '';
	            				for (var i = 0; i < noDeployServer.length; ++i) {
	            					liStr += '<li>' + noDeployServer[i]  +'</li>'
	            				};
	            				divStr = '<div class="group">' +
											'<div>' +
												'<p>下列服务器未部署，是否继续部署：</p>' +
												'<ul>' + liStr +
												'</ul>' +
											'</div>' +
										'</div>';
								$('#noDeployServerList').html(divStr);
		            			$(function () { $('#myDeployModal').modal({
		            				keyboard: true
		            			})});
	            			};

	            		}
	            	}  
	            }  
	        });  
	    },1000); 
		
	    /* 轮训获取结果结束  */
		$.ajax({
			cache:false,
			url:'/deploy_run/{{order.project_order.order_project.id}}/', //请求地址
			type:"POST",  //提交类似
			data:$("#deployRun").serialize(),  //提交参数
			success:function(response){
				btnObj.removeAttr('disabled');
				noDeployServer = response["data"];
				if (response["code"] == "500"){
					clearInterval(interval);
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				}
				
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("部署失败", window.wxc.xcConfirm.typeEnum.error);
	    		clearInterval(interval);
	    	}
		})	
	}	
{% endif %}

	function getVersion(obj,project_branch,project_version) {
		var btnObj = $(obj);
		btnObj.attr('disabled',true);
		$("#version_result").html("正在提交，请稍等。。。");
		$.ajax({
			url:'/deploy_version/'+"{{order.project_order.order_project.id}}/", //请求地址
			type:"POST",  //提交类似
			data:{
				'project_branch':project_branch,
				'project_version':project_version,
				'op':'histroy'
			},  //提交参数
			success:function(response){
				btnObj.removeAttr('disabled');
				if (response["code"] == "200"){
					$("#version_result").html(response["data"]);
				}
				
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("查看失败", window.wxc.xcConfirm.typeEnum.error);
	    		clearInterval(interval);
	    	}
		})	
	}

{% if errorInfo %}
	window.wxc.xcConfirm("{{errorInfo}}", window.wxc.xcConfirm.typeEnum.error);
{% endif %}
</script>

{% endblock %}